package com.jkt.rms.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.jkt.rms.business.SystemRole;
import com.jkt.rms.businessservice.RoleBusinessService;
import com.jkt.rms.commons.utils.RMSException;
import com.jkt.rms.commons.utils.ServiceLocator;
import com.jkt.rms.vo.SystemRoleVO;

public class SystemRoleController extends SimpleFormController {

	private static final String ROLE_MSG = "Role has been created Successfully";
	private static final Logger LOG = Logger.getLogger(SystemRoleController.class);
	private RoleBusinessService roleBusinessService;
	
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws RMSException {
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			 throws Exception {
		LOG.debug("Method onSubmit Start of SystemRoleController");
		SystemRoleVO sysRoleVO = (SystemRoleVO) command;
		if(sysRoleVO != null) {
			sysRoleVO.setUpdatedBy("Admin"); //TO DO Task come from the user session
			roleBusinessService = ServiceLocator.getServiceLocator().locate("roleBusinessService");
			final SystemRole sysRole = roleBusinessService.saveRole(sysRoleVO);
			if(sysRole != null) {
				errors.rejectValue("roleName", "error.allreadyexists", new String[]{"Role Name"}, null);
			}else {
				sysRoleVO.setMessage(ROLE_MSG);
			}
		}
		LOG.debug("Method onSubmit End of SystemRoleController");
		
		return showForm(request, response, errors);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Map<String, SystemRoleVO> referenceData(HttpServletRequest request, Object command,Errors errors) throws Exception {
		final BindException be = (BindException)errors;
		int countError = be.getErrorCount();
		final Map<String, SystemRoleVO> originalModel = be.getModel();  
		final SystemRoleVO originalUser = (SystemRoleVO)originalModel.get("commandBean"); 
		if(originalUser != null && countError == 0) {
			originalUser.setRoleDesc("");
			originalUser.setRoleName("");
		}
			return originalModel;
	}
	
	
}
